<?php
$product_id = intval($product_id);
switch($action){
    case 'save_basic':

        $data = array();
        $cat_id = intval($cat_id);
        $product_name = trim($product_name);
        $product_sn = trim($product_sn);
        empty($product_sn) && $product_sn = 'P'.sprintf('%08d', $_userid).date('Ymd').rand(100, 999) ;

        if ($cat_id <= 1 || empty($category_list[$cat_id])) {
            $status = 0;
            $info = '请选择分类';
        } elseif (empty($product_name)) {
            $status = 0;
            $info = '请选输入商品名称';
        } elseif ($db->result_first("SELECT count(*) FROM `product_list` WHERE `product_sn`='{$product_sn}' AND `id`!='{$product_id}'") > 0) {
            $status = 0;
            $info = '商品货号已存在';
        } else {
            $cat_ids = get_cat_ids($cat_id);
            $designer_id = intval($designer_id);
            $designer_name = trim($designer_name);
            $brand_id = intval($brand_id);
            $brand_name = trim($brand_name);

            $market_price = sprintf('%10.2f', floatval($market_price));
            $shop_price = sprintf('%10.2f', floatval($shop_price));

            if ($is_promote == 'Y') {
                $is_promote = 'Y';
                $promote_price = sprintf('%10.2f', floatval($promote_price));
                $promote_start_time = strtotime($promote_start_time);
                $promote_end_time = strtotime($promote_end_time);
            } else {
                $is_promote = 'N';
                $promote_price = '0.00';
                $promote_start_time = 0;
                $promote_end_time = 0;
            }

            $product_thumb = trim($product_thumb);
            $product_img = trim($product_img);
            $product_desc = trim($product_desc);
            $is_on_sale = $is_on_sale == 'Y' ? 'Y' : 'N';
            $is_alone_sale = $is_alone_sale == 'Y' ? 'Y' : 'N';
            $is_shipping = $is_shipping == 'Y' ? 'Y' : 'N';
            $is_best = $is_best == 'Y' ? 'Y' : 'N';
            $is_new = $is_new == 'Y' ? 'Y' : 'N';
            $is_hot = $is_hot == 'Y' ? 'Y' : 'N';
            $time = time();
            if($product_id > 0 && $db->result_first("SELECT count(*) FROM `product_list` WHERE `id`='{$product_id}'") == 1){
                $insert = false;
                $sql = "UPDATE `product_list`
                    SET
                        `cat_id`='{$cat_id}', `cat_ids`='{$cat_ids}', `user_id`='{$_userid}', `user_name`='{$_username}',
                        `designer_id`='{$designer_id}', `designer_name`='{$designer_name}', `product_sn`='{$product_sn}',
                        `product_name`='{$product_name}', `brand_id`='{$brand_id}',`brand_name`='{$brand_name}',
                        `market_price`='{$market_price}', `shop_price`='{$shop_price}', `promote_price`='{$promote_price}',
                        `promote_start_time`='{$promote_start_time}', `promote_end_time`='{$promote_end_time}',
                        `product_thumb`='{$product_thumb}', `product_img`='{$product_img}', `product_desc`='{$product_desc}',
                        `is_on_sale`='{$is_on_sale}', `is_alone_sale`='{$is_alone_sale}', `is_shipping`='{$is_shipping}',
                        `is_best`='{$is_best}', `is_new`='{$is_new}', `is_hot`='{$is_hot}', `is_promote`='{$is_promote}',
                        `update_time`='{$time}', `status`='NEED_GENERATE'
                    WHERE `id`='{$product_id}'";
            }else{
                $insert = true;
                $sql = "INSERT INTO `product_list`
                    (`cat_id`, `cat_ids`, `user_id`, `user_name`, `designer_id`, `designer_name`, `product_sn`, `product_name`, `brand_id`,
                    `brand_name`, `url`, `market_price`, `shop_price`, `promote_price`, `promote_start_time`, `promote_end_time`,
                    `product_thumb`, `product_img`, `product_desc`, `is_on_sale`, `is_alone_sale`, `is_shipping`,
                    `is_best`, `is_new`, `is_hot`, `is_promote`, `create_time`, `status`)
                    VALUES
                    ('{$cat_id}', '{$cat_ids}', '{$_userid}', '{$_username}', '{$designer_id}', '{$designer_name}', '{$product_sn}', '{$product_name}','{$brand_id}',
                    '{$brand_name}', '', '{$market_price}', '{$shop_price}', '{$promote_price}', '{$promote_start_time}', '{$promote_end_time}',
                    '{$product_thumb}', '{$product_img}', '{$product_desc}', '{$is_on_sale}', '{$is_alone_sale}', '{$is_shipping}',
                    '{$is_best}', '{$is_new}', '{$is_hot}', '{$is_promote}', '{$time}', 'NEED_GENERATE');";
            }
            
            if ($db->query($sql)) {
                $status = 1;
                $info = '保存成功';
                $data['product_id'] = $insert ? $db->insert_id() : $product_id;
                $data['product_sn'] = $product_sn;
            } else {
                $status = 0;
                $info = '保存失败';
            }
        }
        echo ajax_return($status, $info, $data);
        exit();
        break;
    case 'save_desc':
        $content = trim($content);
        $status = $db->result_first("SELECT count(*) FROM `product_list` WHERE `id`='{$product_id}'") == 1
                &&  $db->query("UPDATE `product_desc` SET `status`='BAK' WHERE `prod_id`='{$product_id}' AND `status`='LATEST'")
                &&  $db->query("INSERT INTO `product_desc`(`prod_id`,`content`,`create_time`,`status`) VALUES('{$product_id}','{$content}','".time()."','LATEST')")
                ? 1 : 0;
        echo ajax_return($status);
        exit();
        break;
    case 'save_info':
        if($db->result_first("SELECT count(*) FROM `product_list` WHERE `id`='{$product_id}'") == 1){
            $member_price = sprintf('%10.2f', floatval($member_price));
            $preferential_num = intval($preferential_num);
            $preferential_price = sprintf('%10.2f', floatval($preferential_price));
            $give_integral = intval($give_integral);
            $rank_integral = intval($rank_integral);
            $integral = intval($integral);
            $weight = intval($weight);
            $nums = intval($nums);
            $warn_nums = intval($warn_nums);
            $keywords = trim($keywords);
            $seller_note = trim($seller_note);
            $time = time();

            if($db->result_first("SELECT count(*) FROM `product_info` WHERE `prod_id`='{$product_id}'")){
                $sql = "UPDATE `product_info` SET
                    `member_price`='{$member_price}', `preferential_num`='{$preferential_num}',
                    `preferential_price`='{$preferential_price}', `give_integral`='{$give_integral}', `rank_integral`='{$rank_integral}',
                    `integral`='{$integral}', `weight`='{$weight}', `nums`='{$nums}', `warn_nums`='{$warn_nums}',
                    `keywords`='{$keywords}', `seller_note`='{$seller_note}',`update_time`='{$time}'
                    WHERE `prod_id`='{$product_id}'";
            }else{
                $sql = "INSERT INTO `product_info`
                    (`prod_id`, `member_price`, `preferential_num`, `preferential_price`, `give_integral`,
                    `rank_integral`, `integral`, `weight`, `nums`, `warn_nums`, `keywords`, `seller_note`,
                    `create_time`, `update_time`)
                    VALUES
                    ('{$product_id}', '{$member_price}', '{$preferential_num}', '{$preferential_price}', '{$give_integral}',
                    '{$rank_integral}', '{$integral}', '{$weight}', '{$nums}', '{$warn_nums}', '{$keywords}', '{$seller_note}',
                    '{$time}', '0');";
            }
            $status = $db->query($sql) ? 1 : 0;
        }else{
            $status = 0;
        }
        echo ajax_return($status);
        exit();
        break;
    case 'save_gallery':
        $time = time();
        if($db->result_first("SELECT count(*) FROM `product_list` WHERE `id`='{$product_id}'") == 1){
            $sql = "INSERT INTO `product_gallery`(`prod_id`,`img_url`,`img_desc`,`thumb_url`,`create_time`,`status`)
                VALUES('{$product_id}','{$img_url}','{$img_desc}','{$thumb_url}','{$time}','OK')";
            $status = $db->query($sql) ? 1 : 0;
        }else{
            $status = 0;
        }
        echo ajax_return($status);
        exit();
        break;
    case 'del_gallery':
        $sql = $type == 'DATA' 
                ? "DELETE FROM `product_gallery` WHERE `id`='{$gallery_img_id}'"
                : "UPDATE `product_gallery` SET `status`='DEL' WHERE `id`='{$gallery_img_id}'";
        $status = $db->query($sql) ? 1 : 0;
        echo ajax_return($status);
        exit();
        break;
    case 're_gallery':
        $sql = "UPDATE `product_gallery` SET `status`='OK' WHERE `id`='{$gallery_img_id}'";
        $status = $db->query($sql) ? 1 : 0;
        echo ajax_return($status);
        exit();
        break;
    case 'get_gallery_list':
        include APP_ROOT.'/include/dataview.class.php';

        $sql = "SELECT * FROM `product_gallery` WHERE `prod_id`='{$product_id}' ORDER BY `id` DESC";
        $data = $db->fetch_all($sql);

        $view = new dataview();
	echo $view
		->set_data($data)
                ->add_colume('img_url','原图','15%',callback_img,'center')
                ->add_colume('thumb_url','缩略图','15%',callback_img,'center')
                ->add_colume('img_desc','图片描述','30%',null,'center')
                ->add_colume('create_time','创建时间','10%',callback_time2date,'center')
                ->add_colume('status','状态','15%',callback_status,'center')
                ->add_colume('id','操作','15%',callback_op,'center')
                ->set_table('class','ui-widget ui-widget-content')
                ->set_header('class','ui-widget-header');
        exit();
        break;
    case 'get_data_list'://未关联数据
        $sql = "SELECT `link_1_id`,`link_2_id` FROM `assoc_link`
        WHERE ( `link_1_id` = '{$product_id}' AND `link_1_type` = '{$type}')
           OR ( `link_2_id` = '{$product_id}' AND `link_2_type` = '{$type}')";
        $data = array();
        if($query = $db->query($sql)){
            $assoc_ids = array();
            while($row = $db->fetch_array($query)){
                $assoc_ids[] = $row['link_1_id'] == $product_id ? $row['link_2_id'] : $row['link_1_id'];
            }
            $obj_ids = implode(',',$assoc_ids);
            $cat_ids = $category_list[intval($cat_id)]['childids'];
            switch($type){
                case 'product':
                    $sql = "SELECT `id`,`product_name` as `name` FROM `product_list`
                            WHERE `id` NOT IN({$obj_ids}) AND `cat_id` IN({$cat_ids}) AND `is_alone_sale`='Y' AND `status`!='DEL'";
                    break;
                case 'accessory':
                    $sql = "SELECT `id`,`product_name` as `name` FROM `product_list`
                            WHERE `id` NOT IN({$obj_ids}) AND `cat_id` IN({$cat_ids}) AND `is_alone_sale`='N' AND `status`!='DEL'";
                    break;
                case 'article':
                    $sql = "SELECT `id`,`title` as `name` FROM `article_list`
                            WHERE `id` NOT IN({$obj_ids}) AND `cat_id` IN({$cat_ids}) AND `status`!='DEL'";
                    break;
            }
            $status = 1;
            $data = $db->fetch_all($sql);
        }else{
            $status = 0;
        }
        ajax_return($status, '', $data);
        exit();
        break;
    case 'get_assoc_list'://已关联数据
        $sql = "SELECT `link_1_id`,`link_2_id` FROM `assoc_link`
        WHERE ( `link_1_id` = '{$product_id}' AND `link_2_type` = '{$type}')
           OR ( `link_2_id` = '{$product_id}' AND `link_1_type` = '{$type}')
        ";
        $data = array();
        if($query = $db->query($sql)){
            while($row = $db->fetch_array($query)){
                $data[] = $row['link_1_id'] == $product_id ? $row['link_2_id'] : $row['link_1_id'];
            }
            $status = 1;
        }else{
            $status = 0;
        }

        
        echo ajax_return($status, '', $data);
        exit();
        break;
    default:
        
        include APP_ROOT.'/include/form.func.php';
        
        if(isset($product_id)){
            $product_basic = $db->fetch_first("SELECT * FROM `product_list` WHERE `id`='{$product_id}'");
            $product_desc = $db->fetch_first("SELECT * FROM `product_desc` WHERE `prod_id`='{$product_id}' AND `status`='LATEST' ORDER BY `id` DESC LIMIT 0,1");
            $product_info = $db->fetch_first("SELECT * FROM `product_info` WHERE `prod_id`='{$product_id}' LIMIT 0,1");
            //$product_gallery = $db->fetch_first("SELECT * FROM `product_gallery` WHERE `prod_id`='{$product_id}' LIMIT 0,1");

        }
        $brand_select = mk_select('brand_id', get_option_array('BRAND'), $product_basic['brand_id']);
        
        //CKeditor
        // Include the CKEditor class.
        include_once(APP_ROOT."/include/ckeditor/ckeditor.php");
        // Create a class instance.
        $CKEditor = new CKEditor();//exit("123");
        // Do not print the code directly to the browser, return it instead.
        $CKEditor->returnOutput = true;
        // Path to the CKEditor directory, ideally use an absolute path instead of a relative dir.
        //   $CKEditor->basePath = '/ckeditor/'
        // If not set, CKEditor will try to detect the correct path.
        $CKEditor->basePath = APP_URL.'/include/ckeditor/';
        // Set global configuration (will be used by all instances of CKEditor).
        $CKEditor->config['width'] = '80%';
        // Change default textarea attributes.
        $CKEditor->textareaAttributes = array("cols" => 80, "rows" => 10);
        
        $CKEditor->config['width'] = '100%';
        $CKEditor->config['extraPlugins'] = 'uicolor';
        $CKEditor->config['uiColor'] = '#AABBFF';
        $CKEditor->config['type'] = 'product';
        break;
}
function callback_img($curr,$row){
    return '<a href="'.$curr.'" target="_blank">查看图片</a>';
}
function callback_time2date($curr,$row){
    return $curr == 0 ? '': date('Y-m-d H:i:s',$curr);
}
function callback_status($curr,$row){
    switch($curr){
        case 'OK':
            $return = '<font color="green">正常</font>';
            break;
        case 'DEL':
            $return = '<font color="red">已删除</font>';
            break;
        default:
            $return = '<font color="orange">错误状态</font>';
            break;
    }
    return $return;
}
function callback_op($curr,$row){
    switch($row['status']){
        case 'OK':
            $return = mk_js_onclick('删除','del_gallery',array('status',$curr),'red');
            break;
        case 'DEL':
            $return = mk_js_onclick('恢复','re_gallery',$curr,'green');
            $return .= ' | ';
            $return .= mk_js_onclick('<span title="完全删除">删除</span>','del_gallery',array('DATA',$curr),'blueviolet');
            break;
        default:
            $return = '';
            break;
    }
    return $return;
}
function mk_js_onclick($title,$js_name,$js_var,$font_color = ''){
    !empty($font_color) && $title = '<font color="'.$font_color.'">'.$title.'</font>';
    return ' <a href="javascript:void(0)" onclick="'.$js_name.'(\''.(is_array($js_var) ? implode("','", $js_var) : $js_var).'\')">'.$title.'</a> ';
}
?>
